import {getSongsUrl } from 'api/song'
import {ERR_OK} from "api/config.js"
import {getLyric} from "api/song.js"
import {Base64} from 'js-base64'
export default class Song{
  constructor({id,mid,singer,album,duration,img,url,payplay}){
    this.id = id;
    this.mid = mid;
    this.singer = singer;
    this.album = album;
    this.duration = duration;
    this.img = img;
    this.url = url;
    // this.payplay = payplay
  }
  getLyric(){
    if(this.lyric){
      return Promise.resolve(this.lyric)
    }
    return new Promise((reslove,reject)=>{
      getLyric(this.mid).then((res)=>{
        if(res.retcode == ERR_OK){
          this.lyric = Base64.decode(res.lyric);
          reslove(this.lyric)
        }else{
          reject('no lyric')
        }
      })
    })
    
  }
}

export function createsong(musicData){
  return new Song({
    id:musicData.songid,
    mid:musicData.songmid,
    singer:singerfilter(musicData.singer),
    album:musicData.albumname,
    duration:musicData.interval,
    // payplay:musicData.pay.payplay || 0,//显示歌曲是否允许播放
    img:`https://y.gtimg.cn/music/photo_new/T002R300x300M000${musicData.albummid}.jpg?max_age=2592000`,
   })
}
function singerfilter(singer){
  let singerinfo =[];
  singer.forEach((item)=>{
    singerinfo.push(item.name)
  })
  return singerinfo.join('/');
}

export function processSongsUrl(songs) {
  if (!songs.length) {
    return Promise.resolve(songs)
  }
  return getSongsUrl(songs).then((res) => {
    if (res.code === ERR_OK) {
      let midUrlInfo = res.url_mid.data.midurlinfo
      midUrlInfo.forEach((info, index) => {
        let song = songs[index]
        song.url = `http://dl.stream.qqmusic.qq.com/${info.purl}`
      })
    }
    return songs
  })
}